import { SingleReactiveComponent } from "@/models/reactiveComponent";
import { computed } from "vue";
import { TDatasetServices } from "@/services/datasetServices";
import { TSqlAnalyzeService } from "@/services/sqlAnalyzeServices";
import { TDbServices } from "@/services/dbServices";
import { TUtilsService } from "@/services/utilsServices";

export function getReactData(cpID: string, sql: string, tables: string[], services: {
    dataset: TDatasetServices,
    sqlAnalyze: TSqlAnalyzeService,
    db: TDbServices,
}) {

    return computed(() => {
        let sqlCopy = sql

        return services.db.runOnTransaction(() => {
            tables.forEach(table => {
                const sourceSql = services.dataset.createSql(table, cpID)
                sqlCopy = services.sqlAnalyze.replaceTableToFilterQuery(sqlCopy, table, sourceSql.value)
            })
            return services.db.queryAll(sqlCopy)
        }, 'ROLLBACK')

    })

}


export function getFilterUtils(model: SingleReactiveComponent, services: {
    dataset: TDatasetServices,
    sqlAnalyze: TSqlAnalyzeService,
    db: TDbServices,
    utils: TUtilsService
}) {
    const table = services.sqlAnalyze.getTableNames(model.sqlInfo.sql)[0]

    const sqlQuery = services.utils.createSqlQuery(model.id, model.sqlInfo.sql)

    function getData() {
        return computed(() => sqlQuery.query())
    }

    function removeFilter() {
        services.dataset.removeFilters(model.id, table)

        model.updateInfos.forEach(info => {
            services.dataset.removeFilters(model.id, info.table)
        })
    }

    function addFilter(expr: string) {
        model.updateInfos.forEach(info => {
            services.dataset.addFilter(model.id, info.table, `${info.field} ${expr}`)
        })

    }

    function addFilterWithExprFn(exprFn: (field: string) => string) {
        model.updateInfos.forEach(info => {
            services.dataset.addFilter(model.id, info.table, exprFn(info.field))
        })

    }

    return {
        getData,
        addFilter,
        addFilterWithExprFn,
        removeFilter,
    }
}


